<?php

class Notifaction
{
    private $_dbh;
    private $_logger;

    public function __construct($dbh, $logger = Null)
    {/*{{{*/
        $this->_dbh = $dbh; 
        $this->_logger = $logger; 
    }/*}}}*/

    public function getDeviceTokenList()
    {/*{{{*/
        $sql = "select `token` from bs_devicetoken";
        try
        {
            $list = $this->_dbh->querys($sql);
            return $list;
        }
        catch(Exception $e)
        {
            if($this->_logger)
                $this->_logger->error($e->getFile() . ":" . $e->getLine() . "," . $e->getMessage());
            return false;
        }
    }/*}}}*/

    public function push($message = '')
    {/*{{{*/
        // Put your alert message here:
        if($message == '')
        {
            $message = '老板，请您及时关注我们的最新动态';
        }
        $list = $this->getDeviceTokenList();
        foreach($list as $info)
        {
           $token = $info['token']; 
           $this->pushMessage($message, $token);
        }

        return 0;
    }/*}}}*/

    public function pushMessage($message, $deviceToken)
    {/*{{{*/
        // Put your private key's passphrase here:
        $passphrase = 'cizhuan001';

        ////////////////////////////////////////////////////////////////////////////////

        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', dirname(__FILE__) . '/ck.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

        // Open a connection to the APNS server
        $fp = stream_socket_client(
            'ssl://gateway.sandbox.push.apple.com:2195', $err,
            $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

        if (!$fp)
        {
            if($this->_logger)
                $this->_logger->error($e->getFile() . ":" . $e->getLine() . "," . "Failed to connect: $err $errstr" . PHP_EOL);
            return -2;
        }

        // Create the payload body
        $body['aps'] = array(
            'alert' => $message,
            'sound' => 'default'
        );

        // Encode the payload as JSON
        $payload = json_encode($body);

        // Build the binary notification
        $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

        // Send it to the server
        $result = fwrite($fp, $msg, strlen($msg));

        if (!$result)
        {
            if($this->_logger)
                $this->_logger->error($e->getFile() . ":" . $e->getLine() . "," . "Message not delivered" . PHP_EOL);
            $rst = -3;
        }
        else
            $rst = 0;

        // Close the connection to the server
        fclose($fp);
        return $rst;
    }/*}}}*/

    public function save($token)
    {/*{{{*/
        $sql = "insert ignore into bs_devicetoken set `token` = ?";
        $val[] = $token;
        try
        {
            $this->_dbh->beginTrans();
            $this->_dbh->execute($sql, $val); 
            $lastId = $this->_dbh->getLastInsertID();
            $this->_dbh->commit();

            return $lastId;
        }
        catch(Exception $e)
        {
            $this->_dbh->rollback();
            if($this->_logger)
                $this->_logger->error($e->getFile() . ":" . $e->getLine() . "," . $e->getMessage());
            if($e->errorInfo[1] == 1062 && $e->errorInfo[0] == "23000")
            {
                // Duplicate key
                return -1;
            }
            else
            {
                // Unknow error
                return -100;
            }
        }
    }/*}}}*/
}
